
#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#include <memory>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "InetAddr.hpp"
#include "socket.hpp"

using namespace std;
using namespace socket_net;

const static int defaultfd = -1;

using http_t = function<string(string request)>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

class TcpServer;
class ThreadData
{
public:
    ThreadData(sock_sptr fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), Clientaddr(addr), self(s)
    {
    }
    sock_sptr sockfd;
    InetAddr Clientaddr;
    TcpServer *self;
};
class TcpServer
{
public:
    TcpServer(int port, http_t service)
        : _localaddr("0", port),         
          _listensock(make_unique<TcpSocket>()),
          _http_service(service),
          _isrunning(false)
    {
        _listensock->BuildListenSocket(_localaddr);
    }
    // 类类成员函数用static
    static void *HanderSock(void *args)
    {
        pthread_detach(pthread_self()); // 线程分离是实现多线程情况的一种方式之一
        ThreadData *td = static_cast<ThreadData *>(args);
        string request,response;
        ssize_t n = td->sockfd->Recv(&request); // 请求
        if (n > 0)
        {
            response=td->self->_http_service(request);
            td->sockfd->Send(response); // 应答
        }
        td->sockfd->Close();
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peeraddr;
            sock_sptr normalsock = _listensock->Acceptaddr(&peeraddr);
            if (normalsock == nullptr)
                continue;
            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HanderSock, td);
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    http_t _http_service;
};